var express = require('express');
var router = express.Router();

const loginLogService = require("../../services/admin/loginLogService");

function __toParams(log){
    return {
        id: log.id,
        is: log.id + "_",
        ip: log.ip,
        user_name: log.user_name,
        name: log.name,
        login_time: log.login_time
    };
}

module.exports = router;

/* GET users listing. */
router.get('/', (req, res, next) => {
    res.render('admin/login_log', {
        user: req.session.user,
        menus: req.session.menus,
        menu_active: req.session.menu_active['/login_log'] || {},
        title: '登录日志'
    });
});

router.get('/load', function(req, res, next) {
    var {search, start, length, draw} = req.query;
    if (!start || !length || !draw) {
        return res.status(401).json("invoke error!");
    }

    var keywords = search?search.value.trim():null;
    var start = parseInt(start) || 0;
    var length = parseInt(length) || 0;
    var draw = parseInt(draw) || 0;

    loginLogService.getLoginLogs(keywords, start, length, function (err, data) {
        if (!!err){
            return res.status(200).json(err);
        }

        var result = { draw: draw, recordsTotal: data.count, recordsFiltered: data.count, data: [] };
        data.rows.forEach(function (log) {
            result.data.push(__toParams(log));
        });

        return res.status(200).json(result);
    });
});

router.delete('/delete', async(req, res, next) => {
    const ids = req.body.ids;
    if (!ids || ids.trim().length == 0) {
        return res.status(200).json({error: 1, msg: '删除失败，必须选择一项'});
    }
    loginLogService.deleteByIds(ids.split(","), function (err, result) {
        if (!!err){
            return res.status(200).json(err);
        }
        return res.status(200).json({ error: 0, msg: "ok" });
    });
});
